<!-- 详情页 -->
<template>
  <div>
    <div class="detail" v-if="detail">
      <Top></Top>
      <div class="banner" v-if="detail.item">
        <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
          <van-swipe-item v-for="(item, idx) in detail.item.images" :key="idx">
            <img :src="item" alt="" />
          </van-swipe-item>
        </van-swipe>
      </div>
      <div class="wCen" v-if="detail.item">
        <!-- 价格标题 -->
        <div class="titleBox">
          <div class="card">
            <div class="title">{{ title }}</div>
            <div class="priceBox">
              <div class="priceOld">￥{{ priceOld }}</div>
              <div class="price">￥{{ priceCurrent }}</div>
            </div>
            <!-- sku_id:{{ sku_id }} -->
          </div>
        </div>
        <!-- 规格 -->
        <div class="specs">
          <div class="card">
            <div class="specs_l">选择</div>
            <div class="specs_r" @click="showSpecs = true">
              {{ sku_id ? currentSku : detail.item.sku_text }}
              <van-icon name="arrow" />
            </div>
          </div>
        </div>
        <!-- 商城 -->
        <div class="shop" v-if="seller">
          <div class="card">
            <div class="shop_t">
              <div class="shop_t_l">
                <!-- <van-icon name="send-gift-o" size="40" /> -->
                <img :src="seller.shop_icon" alt="" class="img" />
              </div>
              <div class="shop_t_r">
                <div class="name">{{ seller.shop_name }}</div>
                <div>
                  综合 <van-rate v-model="rate" color="#ffd21e" readonly /><span
                    class="rateTxt"
                    >{{ rate }}</span
                  >
                </div>
              </div>
            </div>
            <div class="shop_b">
              <span
                class="shop_b_item"
                v-for="(item, idx) in seller.evaluates"
                :key="idx"
                >{{ item.title }} {{ item.score }}</span
              >
            </div>
            <!-- 详情 -->
            <div class="detailCon">
              <div class="card">
                <div class="desc">
                  <div
                    class="desc_item"
                    v-for="(item, idx) in descBaseList"
                    :key="idx"
                  >
                    {{
                      JSON.stringify(item)
                        .replace(/{|}|"/g, "")
                        .replace(":", "：")
                    }}
                  </div>
                </div>
                <div style="padding: 20px 0">
                  <iframe
                    :src="detail.item.taobao_desc_url"
                    height="1600px"
                    width="320"
                    frameborder="0"
                    scrolling="auto"
                  ></iframe>
                  <!-- <img :src="detail.item.taobao_desc_url" alt="" /> -->
                  <!-- <img
                  :src="item"
                  alt=""
                  v-for="(item, idx) in imgs"
                  :key="idx"
                /> -->
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 底部 -->
        <div class="bottom">
          <div class="btn customer" @click="handleCustomer">
            <img src="@/assets/imgs/customer.svg" class="img" />
            客服
          </div>
          <div class="btn join" @click="showSpecs = true">加入购物车</div>
          <div class="btn go" @click="handle2Cart">购物车</div>
        </div>
      </div>
      <van-action-sheet v-model="showSpecs" title="选择规格">
        <div class="specsBox">
          <div class="content">
            <p>{{ title }}</p>
            <p>价格：￥{{ priceCurrent }}</p>
            <p>{{ currentSku }}</p>
            <div class="content_i" v-for="item in specsList" :key="item.pid">
              <p class="name">{{ item.name }}</p>
              <div
                class="item"
                :class="{ active: currentPidVid[item.pid] == itemJ.vid }"
                v-for="itemJ in item.values"
                :key="itemJ.vid"
                @click="
                  handleSelect(item.pid, itemJ.vid, item.name, itemJ.name)
                "
              >
                <img :src="itemJ.image" alt="" class="img" v-if="itemJ.image" />
                <span>{{ itemJ.name }}</span>
              </div>
            </div>
            <div class="btnBox">
              <div @click="selectSure" class="btn">加入购物车</div>
            </div>
          </div>
        </div>
      </van-action-sheet>
    </div>
  </div>
</template>
<script>
import { Toast, Dialog } from "vant";
import localStore from "@/libs/localstore";
import config from "@/libs/config";
import axios from "axios";
import Top from "@/components/Top.vue";
export default {
  name: "Detail",
  components: { Top },
  data() {
    return {
      host:config.host,
      detail: undefined,
      showSpecs: false, //显示规格弹框
      currentPidVid: {},
      currentSkuObj: {}, //当前选择的sku
    };
  },
  computed: {
    id() {
      return this.$route.query.id;
    },
    // 商品标题
    title() {
      if (!this.detail) return "";
      return this.detail.item && this.detail.item.title;
    },
    // 原来价格
    priceOld() {
      if (!this.detail) return "9999999.99";
      const mock_data = this.detail.mock_data;
      let result = "";
      if (this.sku_id) {
        result = mock_data.skuCore.sku2info[this.sku_id]["price"]["priceText"];
      } else {
        result = mock_data.price.price.priceText;
      }
      return result;
    },
    // 当前价格
    priceCurrent() {
      if (!this.detail) return "9999999.99";
      const mock_data = this.detail.api_stack[0].value;
      let result = "";
      if (this.sku_id) {
        result = mock_data.skuCore.sku2info[this.sku_id]["price"]["priceText"];
      } else {
        result = mock_data.skuCore.sku2info["0"]["price"]["priceText"];
      }
      return result;
    },
    seller() {
      return this.detail.seller;
    },
    rate() {
      return 4.0;
    },
    // 详情图列表
    imgs() {
      // return [require("@/assets/imgs/1.png"), require("@/assets/imgs/2.png")];
      return [];
    },
    // 描述信息
    descBaseList() {
      return this.detail.props.group_props[0]["基本信息"];
    },
    // 规格列表
    specsList() {
      return this.detail.sku_base && this.detail.sku_base.props;
    },
    // 规格
    skus() {
      return this.detail.sku_base && this.detail.sku_base.skus;
    },
    // 拼接后生成sku_id
    sku_id() {
      const pidVid = this.currentPidVid;
      let prop_path_arr = [];
      for (let i in pidVid) {
        prop_path_arr.push(i + ":" + pidVid[i]);
      }
      let prop_path = prop_path_arr.join(";");
      let item = this.skus.filter((item) => {
        return item.prop_path == prop_path;
      });
      if (item && item.length > 0) {
        return item[0]["sku_id"];
      }
    },
    // 当前选择的sku
    currentSku() {
      const obj = this.currentSkuObj;
      let arr = [];
      for (let i in obj) {
        arr.push(obj[i]);
      }
      return arr.length > 0 ? arr.join(";") : "";
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    getData() {
      this.$store.commit("setShowLoading", true);
    
      var myHeaders = new Headers();
      myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");

      var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
      };
      fetch(`${this.host}/api/v1/list/${this.id}?type=TB`,requestOptions).then(res=>res.json())
        .then((result) => {
          console.log(result)
          if (result.statusCode == 200) {
            this.detail = result.data;
            console
              .log("detail", this.detail);
            this.$store.commit("setShowLoading", false);
          }
        })
        .catch((error) => console.log("error", error));
    },
    // 客服
    handleCustomer() {
      Dialog.alert({
        title: "提示",
        message: "客服功能正在开发中,敬请期待！",
      }).then(() => {
        // on close
      });
    },
    // 去往购物车
    handle2Cart() {
      this.$router.replace("/cart");
    },
    // 选择规格
    handleSelect(pid, vid, nameType, name) {
      this.$set(this.currentPidVid, pid, vid);
      this.$set(this.currentSkuObj, pid, `${nameType}:${name}`);
    },
    // 选择规格后
    selectSure() {
      if (JSON.stringify(this.currentPidVid) === "{}") {
        Toast("请选择规格");
        return;
      }
      // console.log(this.currentPidVid);
      this.submitData();
      this.showSpecs = false;
    },
    // 添加购物车
    submitData() {
      if(!this.detail) return
      // 封装购物车数据
      const obj = {
        shopName: this.seller.shop_name,
        id: this.id,
        list: [
          {
            title: this.title,
            price: this.priceCurrent,
            id:this.id,
            image:
              this.detail.item.images &&
              this.detail.item.images.length > 0 &&
              this.detail.item.images[0],
            count: 1,
            sku_id: this.sku_id,
            skuTxt: this.currentSku,
            isChecked: false,
          },
        ],
      };
      let cartTaobao = JSON.parse(localStore.getItem("cartTaobao")) || [];
      // 如果购物车已经存在数据，取出数据,push,然后再保存
      if (cartTaobao && cartTaobao.length > 0) {
        this.joinCartData(cartTaobao, obj);
        localStore.setItem("cartTaobao", JSON.stringify(cartTaobao));
        // 否则直接保存
      } else {
        localStore.setItem("cartTaobao", JSON.stringify([obj]));
      }
    },
    // 将数据加入购物的数据内,需要进行数据处理
    // 如果原来店铺已有一条数据，需要合并店铺
    joinCartData(cart, obj) {
      // 判断是否是同一店铺
      //  如果原来数据里面没有这个店铺，直接插入这条数据
      if (cart.filter(item=>item.id===obj.id).length === 0) {
        cart.push(obj);
      } else {
        // 否则找到这个店铺加入数据
        for (let i = 0; i < cart.length; i++) {
          if (cart[i].id === obj.id) {
            // 合并数据
            cart[i].list.push(obj.list[0]);
            break;
          }
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.detail {
  min-height: 100vh;
  background-color: #f5f5f5;
  position: relative;

  .titleBox {
    .priceOld {
      text-decoration: line-through;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .priceBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 10px;
    }
    .price {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #e4393c;
    }
    .title {
      font-size: 20px;
      font-weight: bold;
    }
  }
  .specs {
    .card {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      .specs_l {
        font-size: 14px;
        font-weight: bold;
        color: #a9a9a9;
        flex-shrink: 0;
        margin-right: 20px;
      }
      .specs_r {
        color: #313131;
        font-size: 14px;
        line-height: 1em;
        text-overflow: ellipsis;
        // 不换行
        white-space: nowrap;
        overflow: hidden;
      }
    }
  }
  .shop {
    &_t {
      display: flex;
      align-items: center;
      padding: 20px 0;
      &_l {
        padding-right: 10px;
        .img {
          width: 80px;
        }
      }
      &_r {
      }
    }
    &_b {
      &_item {
        &:not(:first-child) {
          margin-left: 20px;
        }
      }
    }
    .detailCon {
      .desc {
        display: flex;
        flex-wrap: wrap;
        &_item {
          flex: 0 0 100%;
          width: 100%;
          overflow: hidden;
          white-space: nowrap;
          margin-bottom: 10px;
          text-overflow: ellipsis;
          margin-left: -8px;
        }
      }
    }
    // 店铺名称
    .name {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .rateTxt {
      margin-left: 10px;
    }
  }
  .bottom {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    border-top: 1px solid #f2f4f6;
    box-shadow: 0 0 5px #f2f4f6;
    padding: 10px 15px;
    left: 0;
    right: 0;
    .btn {
      margin-left: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      &.customer {
        flex-direction: column;
        margin-right: 20px;
        font-size: 14px;
        .img {
          width: 24px;
        }
      }
      &.join {
        $h: 50px;
        $c: #ffa351;
        // border:2px solid #ffa351;
        background-color: $c;
        color: #fff;
        font-weight: bold;
        border-radius: $h;
        height: $h;
        cursor: pointer;
        flex-shrink: 0;
        padding: 0 20px;
      }
      &.go {
        $h: 50px;
        $c: #ffa351;
        border: 2px solid #ffa351;
        color: #ffa351;
        font-weight: bold;
        border-radius: $h;
        height: $h;
        cursor: pointer;
        flex-shrink: 0;
        padding: 0 20px;
      }
    }
  }
  // 规格选择列表
  .specsBox {
    overflow-y: auto;
    height: 600px;
    overflow-x: hidden;
    padding: 20px;
    .content {
      &_i {
        margin-bottom: 20px;
      }
      .name {
        font-size: 16px;
        font-weight: bold;
        margin: 0;
        margin-bottom: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .item {
        margin-bottom: 10px;
        border: 1px solid transparent;
        display: inline-flex;
        align-items: center;
        padding-right: 10px;
        &.active {
          border-color: #333;
        }
        .img {
          width: 40px;
          margin-right: 10px;
        }
      }
      .btnBox {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .btn {
          $h: 50px;
          $c: #ffa351;
          border: 2px solid #ffa351;
          color: $c;
          font-weight: bold;
          border-radius: $h;
          height: $h;
          width: 140px;
          cursor: pointer;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }
  }
}
.card {
  border-radius: 6px;
  background-color: #fff;
  margin-bottom: 20px;
  padding: 10px;
}
</style>
